package cn.est.utils;

import cn.est.config.OssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springfox.documentation.service.ApiListing;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @ClassName OssUtils
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2021/4/16 8:44
 * @Version 1.0
 **/
@Component
public class OssUtils {



    @Autowired
    private OssConfig ossConfig;


    /**
     * 获取ossclient客户端
     * @return
     */
    public OSS getOssClient(){

        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndPoint(), ossConfig.getAccesskeyid(), ossConfig.getAccesskeysecret());
        return  ossClient;
    }


    public String uploadByStream(File file , String fileName){
        String strResult="";
        OSS ossclient =null;
        try {
            InputStream is=new FileInputStream(file);
            ossclient=getOssClient();
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");
            PutObjectResult putObjectResult=ossclient.putObject(ossConfig.getBucketName(),fileName,is,meta);
            strResult=putObjectResult.getETag();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e){
            if(ossclient!=null){
                ossclient.shutdown();
            }
        }
        return strResult;
    }


    public void deleteFile(String bucketName,String fileName){
        OSS ossClient=getOssClient();
        ossClient.deleteObject(bucketName,fileName);
        ossClient.shutdown();
    }

    // /est/model/aaa.jpg
    public void downloadFile(String fileName,HttpServletResponse response) throws IOException {

        OSS ossClient=getOssClient();
        //        // 设置响应头为下载
//        response.setContentType("application/x-download");
//        // 设置下载的文件名
//        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
//        response.setCharacterEncoding("UTF-8");
        // 文件名以附件的形式下载
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 获取oss的Bucket名称
        String bucketName =ossConfig.getBucketName();
        // 获取oss目标文件夹
        String filehost = "est/model";
        // 日期目录
        // 注意，这里虽然写成这种固定获取日期目录的形式，逻辑上确实存在问题，但是实际上，filePath的日期目录应该是从数据库查询的

        String fileKey = filehost +  "/" + fileName;
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, fileKey);
        try {
            // 读取文件内容。
            InputStream inputStream = ossObject.getObjectContent();
            BufferedInputStream in = new BufferedInputStream(inputStream);// 把输入流放入缓存流

            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream out = new BufferedOutputStream(outputStream);// 把输出流放入缓存流

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }

        } catch (Exception e) {

        }

    }
}
